package com.demo.demo_scan;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class XzingApp {

	public static void main(String[] args) {
		try {
			String dir = System.getProperty("user.dir").replace("/", "\\");
			String imgUrl = dir.concat("\\img\\3t1dstRoi-0-1-2.jpg");
			File imageFile = new File(imgUrl);
			BufferedImage bufferedImage = ImageIO.read(imageFile);

			Result result = decodeQRCode(bufferedImage);

	        if (result != null) {

	            System.out.println("Decoded text: " + result.getText());
	            
	            // 获取位置信息

	            ResultPoint[] points = result.getResultPoints();

	            int[] position = new int[8]; // 三个点，每个点两个坐标
	            

	            for (int i = 0; i < points.length; i++) {

	                ResultPoint point = points[i];

	                position[i * 2] = (int) point.getX();

	                position[i * 2 + 1] = (int) point.getY();

	            }


	            // 裁剪图片
	            position[0]=position[0]-20;
	            position[1]=position[1]+20;
	            position[3]=position[3]-20;
	            position[4]=position[4]+20;
	            
	            BufferedImage croppedImage = cropImage(bufferedImage, position);

	            // 保存裁剪后的图片
	            String outimgUrl = dir.concat("\\img\\3t1dstRoi-1-2-3-1.jpg");
	            ImageIO.write(croppedImage, "jpg", new File(outimgUrl));

	        }
		} catch (IOException | NotFoundException e) {
			e.printStackTrace();
		}
	}

	private static Result decodeQRCode(BufferedImage image) throws NotFoundException {
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
		return new MultiFormatReader().decode(bitmap, hints);
	}

	private static BufferedImage cropImage(BufferedImage originalImage, int[] position) {
		// 这里简单地计算一个矩形区域作为示例
		int left = Math.min(position[0], Math.min(position[2], position[4]));
		int top = Math.min(position[1], Math.min(position[3], position[5]));
		int right = Math.max(position[0], Math.max(position[2], position[4]));
		int bottom = Math.max(position[1], Math.max(position[3], position[5]));

		return originalImage.getSubimage(left, top, right - left, bottom - top);
	}
}